package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import yxt.push.org.androidpn.client.ServiceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.alipay.Keys;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**医院选择
 * @author Administrator
 *
 */
public class HospitalChoice extends Activity
{
	private RelativeLayout yylv, dqlv;
	private Button nextbutton;
	private HospitalChoice oThis = this;
	private CustomProgressDialog proDialog;// 加载框
	private TextView text_dq,text_yymc,text_yyid,text_dqmc,text_dqid,text_yyurl,text_yybm,
	text_xmpport,text_apikey,text_hosturl,text_hospitalid;
	MyApplication myApp;
	public ServiceManager serviceManager;
	private String yyid;

	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.hospitalchoice);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		// 初始化view
		findView();

		// 点击事件
		setOnClick();

	}

	private void setOnClick()
	{
		dqlv.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent(oThis, HospitalDq.class);
				oThis.startActivityForResult(intent, 1);

			}
		});
		yylv.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				if (text_dqid.getText() != null && !text_dqid.getText().equals(""))
				{

					Intent intent = new Intent(oThis, HospitalYy.class);
					intent.putExtra("dq_id", text_dqid.getText().toString());
					oThis.startActivityForResult(intent, 2);

				}
				else
				{
					Toast.makeText(oThis, "请先选择地区", Toast.LENGTH_SHORT).show();
				}

			}
		});

		nextbutton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				if (text_yyid.getText() != null && !text_yyid.getText().equals(""))
				{
					myApp.setYydm(text_yyid.getText().toString());
					myApp.setYymc(text_yymc.getText().toString());
					myApp.setDqdm(text_dqid.getText().toString());
					myApp.setDqmc(text_dqmc.getText().toString());
					// 把地区及医院信息加入缓存
					SharedPreferences settings = getSharedPreferences("yyxx_file", 0);
					// 获得可编辑对象
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("dqmc", text_dqmc.getText().toString());
					editor.putString("dqid", text_dqid.getText().toString());
					
					editor.putString("hostid", text_hospitalid.getText().toString());
					editor.putString("yymc", text_yymc.getText().toString());
					editor.putString("yyid", text_yyid.getText().toString());
					editor.putString("yyurl", text_yyurl.getText().toString());
					editor.putString("gnbm", text_yybm.getText().toString());
					editor.putString("xmpport", text_xmpport.getText().toString());
					editor.putString("apikey", text_apikey.getText().toString());
					editor.putString("hosturl", text_hosturl.getText().toString());
					editor.commit();

					URLUtils.HOST = text_yyurl.getText().toString();
					URLUtils.HOSTMES = text_hosturl.getText().toString();
					URLUtils.APIKEY = text_apikey.getText().toString();
					URLUtils.POST = text_xmpport.getText().toString();
					
					
					// 创建新的服务

					proDialog = CustomProgressDialog.createDialog(oThis);
					proDialog.setMessage("数据加载中...");
					proDialog.show();
					proDialog.setCanceledOnTouchOutside(false);
					Thread login = new LoginHandler();
					login.start();
				}
				else
				{
					Toast.makeText(oThis, "请选择医院", Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	// 开启一个线程类
	private class LoginHandler extends Thread
	{
		// 将登录不成功的消息传递到UI线程
		private void loginUnSuccess(String msg)
		{
			proDialog.dismiss();
			// clearPreferences();
			Message message = new Message();
			Bundle bundle = new Bundle();
			bundle.putInt("type", 0);
			bundle.putString("msg", msg);
			message.setData(bundle);
			UIHandler.sendMessage(message);
		}

		@Override
		public void run()
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("userid", myApp.getAccount()));
			JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.HOSURLLOGIN, params);
			try
			{
				if (res == null)
				{
					loginUnSuccess("连接服务器失败");
				}
				else if (res.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					loginUnSuccess("连接服务器失败");
				}
				else
				{
					Intent intent = new Intent();
					intent.putExtra("yyimg", res.getString("imginfo"));// 初始化图片名称
					myApp.setFamilysfzhs(res.getString("sfzhs"));// 获取家庭账号下绑定的身份证

					// 读取缓存数据,如果缓存有数据，则读取缓存
					SharedPreferences settings = getSharedPreferences("users_file", 0);

					String username = settings.getString("username", "");
					String sfzh = settings.getString("sfzh", "");
					String sjh = settings.getString("sjh", "");
					String xb = settings.getString("xb", "");
					String drzh = settings.getString("drzh", "");
					String memberid = settings.getString("memberid", "");//取家庭成员id
					if (drzh != null && drzh.equals(myApp.getAccount()))
					{// 同一账号
						
						if (new JSONArray(res.getString("userinfo")).length() > 0)
						{
							JSONArray items = new JSONArray(res.getString("userinfo"));
							int m = -1;
							for (int j = 0; j < items.length(); j++)
							{
								JSONObject jobj = items.getJSONObject(j);
								if(memberid!=null&&jobj.getString("id").equals(memberid)){//判断缓存成员有没有被删除
									m = j;
								}
							}
							if(m==-1){//没有匹配，默认第一个成员
								JSONObject jobj = items.getJSONObject(0);
								myApp.setHzxm(jobj.getString("zsxm"));
								myApp.setSfzh(jobj.getString("sfzh"));
								myApp.setSex(jobj.getString("sex"));
								myApp.setSjh(jobj.getString("sjh"));
								myApp.setMemberid(jobj.getString("id"));
							}else{
								JSONObject jobj = items.getJSONObject(m);
								myApp.setHzxm(jobj.getString("zsxm"));
								myApp.setSfzh(jobj.getString("sfzh"));
								myApp.setSex(jobj.getString("sex"));
								myApp.setSjh(jobj.getString("sjh"));
								myApp.setMemberid(jobj.getString("id"));
							}
						}else{//没有成员返回，成员全部被删除
							myApp.setHzxm("");
							myApp.setSfzh("");
							myApp.setSex("");
							myApp.setSjh("");
							myApp.setMemberid("");
						}
						
					}
					else//默认选择第一个家庭成员
					{
						if (new JSONArray(res.getString("userinfo")).length() > 0)
						{
							JSONArray items = new JSONArray(res.getString("userinfo"));
							
							JSONObject jobj = items.getJSONObject(0);
							myApp.setHzxm(jobj.getString("zsxm"));
							myApp.setSfzh(jobj.getString("sfzh"));
							myApp.setSex(jobj.getString("sex"));
							myApp.setSjh(jobj.getString("sjh"));
							myApp.setMemberid(jobj.getString("id"));
							
						}else{//没有成员返回，或成员全部被删除
							myApp.setHzxm("");
							myApp.setSfzh("");
							myApp.setSex("");
							myApp.setSjh("");
							myApp.setMemberid("");
						}
					}

					intent.putExtra("gnbm", text_yybm.getText().toString());// 初始化图片名称
					intent.setClass(HospitalChoice.this, Mainmean.class);

					startActivity(intent);

					proDialog.dismiss();
				}
			}
			catch (JSONException e)
			{
				// loginUnSuccess(e.toString());
			}
		}
	}

	// 处理不成功传回来的消息
	Handler UIHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case 0:
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(HospitalChoice.this);
					builder.setMessage(msg.getData().getString("msg")).setCancelable(false)
							.setPositiveButton("确定", new DialogInterface.OnClickListener()
							{
								public void onClick(DialogInterface dialog, int id)
								{
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
					break;
				}
				default:
				{}
			}
		}
	};

	private void findView()
	{
		dqlv = (RelativeLayout) this.findViewById(R.id.lv_dq);
		yylv = (RelativeLayout) this.findViewById(R.id.lv_yy);
		nextbutton = (Button) this.findViewById(R.id.next_button);
		text_yymc = (TextView)this.findViewById(R.id.text_yymc);
		text_yyid = (TextView)this.findViewById(R.id.text_yyid);
		text_dqmc = (TextView)this.findViewById(R.id.text_dqmc);
		text_dqid = (TextView)this.findViewById(R.id.text_dqid);
		
		text_yyurl = (TextView)this.findViewById(R.id.text_yyurl);
		text_yybm = (TextView)this.findViewById(R.id.text_yybm);
		text_xmpport = (TextView)this.findViewById(R.id.text_xmpport);
		text_apikey = (TextView)this.findViewById(R.id.text_apikey);
		text_hosturl = (TextView)this.findViewById(R.id.text_hosturl);
		text_hospitalid = (TextView)this.findViewById(R.id.text_hospitalid);
		
		//读取缓存数据
		SharedPreferences settings = getSharedPreferences("yyxx_file", 0);
		String dqmc = settings.getString("dqmc", "");
		String dqid = settings.getString("dqid", "");
		String hostid = settings.getString("hostid", "");
		
		if (dqid != null && !dqid.equals(""))
		{
			text_dqid.setText(dqid);
			text_dqmc.setText(dqmc);

		}
		//获取医院id
		if (hostid != null && !hostid.equals(""))
		{
			this.yyid = hostid;
			GetData();

		}
		
	}

	/*
	 * (non-Javadoc) 得到传回的ks
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // TODO Auto-generated method stub  
        super.onActivityResult(requestCode, resultCode, data);
        String dq_mc="",dq_id="",yy_mc="",yy_id="",yy_yyid="";
        switch (requestCode) {  
        case 1:  
        	dq_mc = data.getStringExtra("dq_mc")==null?"":data.getStringExtra("dq_mc");// 取出传回来的数据  
     		dq_id = data.getStringExtra("dq_id")==null?"":data.getStringExtra("dq_id");
            break;  
        case 2:  
        	yy_mc = data.getStringExtra("yy_mc")==null?"":data.getStringExtra("yy_mc");// 取出传回来的数据  
     		yy_id = data.getStringExtra("yy_id")==null?"":data.getStringExtra("yy_id");
     		yy_yyid = data.getStringExtra("yy_yyid")==null?"":data.getStringExtra("yy_yyid");
     		
            break;  
        
        }  
       
		if(!dq_id.equals("")){
			text_dqmc.setText(dq_mc+" ");
			text_dqid.setText(dq_id);
			text_yymc.setText("");
			text_yyid.setText("");
		}
		if (!yy_id.equals(""))
		{
			this.yyid = yy_yyid;
			//选择医院后清空用户缓存，使点击下一步进入主界面时，重新获取当前成员
			SharedPreferences usesrsettings = getSharedPreferences("users_file", 0);
			// 获得可编辑对象
			SharedPreferences.Editor usereditor = usesrsettings.edit();
			usereditor.clear();
			usereditor.commit();
			GetData();
		}

	}
	
	private void GetData() {
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData() {
		try {
			Message msg = myHandler.obtainMessage();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("yyid", yyid));
			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOSTMAIN + URLUtils.GETYYXX, ls);
			JSONArray jsonArr;
			Map<String, Object> map_yy; // 医院map
			List<Map<String, Object>> list_yy = new ArrayList<Map<String, Object>>();// 医院list
			if (json != null && !json.equals("")) {
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (json.getString("yyinfo").length() > 0)
					{
						// 获取地区信息
						jsonArr = new JSONArray(json.getString("yyinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++) {
							map_yy = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							// previewId = js.getString("PId");
							map_yy.put("id", js.getString("id"));
							map_yy.put("yydm", js.getString("yydm"));
							map_yy.put("yymc", js.getString("yymc"));
							map_yy.put("visiturl", "http://"+js.getString("visiturl"));
							map_yy.put("bm", js.getString("bm"));
							map_yy.put("xmpport", js.getString("xmpport"));
							map_yy.put("apikey", js.getString("apikey"));
							map_yy.put("hosturl", js.getString("hosturl"));
							
							map_yy.put("partner", js.getString("partner"));
							map_yy.put("seller", js.getString("seller"));
							map_yy.put("privatekey", js.getString("privatekey"));
							
							map_yy.put("mzpayflag", js.getString("mzpayflag"));
							map_yy.put("zypayflag", js.getString("zypayflag"));
							map_yy.put("ghpayflag", js.getString("ghpayflag"));
							
							map_yy.put("jzhflag", js.getString("jzhflag"));
							map_yy.put("messageflag", js.getString("messageflag"));
							list_yy.add(map_yy);
						}

						msg.what = 0;
						msg.obj = list_yy;
					}else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}
				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}
	
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接错误！";
			}
			myHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if(msg.obj!=null){
						List<Map<String, Object>> list_yy= (List<Map<String, Object>>) msg.obj;
						if(list_yy.size()>0){
							Map<String, Object> map_yy = list_yy.get(0);
								
								text_yymc.setText(map_yy.get("yymc").toString() + " ");
								text_yyid.setText(map_yy.get("yydm").toString());
								text_yyurl.setText(map_yy.get("visiturl").toString());
								text_yybm.setText(map_yy.get("bm").toString());
								text_xmpport.setText(map_yy.get("xmpport").toString());
								text_apikey.setText(map_yy.get("apikey").toString());
								text_hosturl.setText(map_yy.get("hosturl").toString());
								text_hospitalid.setText(map_yy.get("id").toString());
								
								myApp.setMzpayflag(map_yy.get("mzpayflag").toString());
								myApp.setZypayflag(map_yy.get("zypayflag").toString());
								myApp.setGhpayflag(map_yy.get("ghpayflag").toString());
								
								myApp.setJzhflag(map_yy.get("jzhflag").toString());
								myApp.setMessageflag(map_yy.get("messageflag").toString());
								
								Keys.setDEFAULT_PARTNER(map_yy.get("partner").toString());
								Keys.setDEFAULT_SELLER(map_yy.get("seller").toString());
								Keys.setPRIVATE(map_yy.get("privatekey").toString());

								
						}
					
					}
					break;
				default:
					break;
			}
		};
	};



}
